package com.forum.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.forum.annotation.IgnoreAuth;
import com.forum.entity.news;
import com.forum.service.NewsService;
import com.forum.utils.MPUtil;
import com.forum.utils.PageUtils;
import com.forum.utils.R;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

/**
 * @ClassNameNewsControoler
 * @Author 张继成
 * @Date 2023/12/4 23:09
 */

@RestController
@RequestMapping("/news")
@Api(tags = "相关资讯控制")
@Slf4j
public class NewsController {

    @Autowired
    private NewsService newsService;

    /**
     * 前端列表
     */
    @IgnoreAuth
    @GetMapping("/list")
   // @SuppressWarnings("unchecked")
    public R list(@RequestParam Map<String, Object> params, news news,
                  HttpServletRequest request){
        EntityWrapper<news> ew = new EntityWrapper<news>();

        PageUtils page = newsService.QueryPage(params, MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(ew, news), params), params));
        return R.ok().put("data", page);
    }

    @GetMapping("/page")
    public R page(@RequestParam Map<String , Object> params, news news,
                  HttpServletRequest httpServletRequest){
        EntityWrapper<news> newsEntityWrapper = new EntityWrapper<>();
        PageUtils page = newsService.QueryPage(params, MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(newsEntityWrapper, news), params), params));

        return R.ok().put("data",page);
    }

    /**
     * 单条信息
     * @param id
     * @return
     */
    @GetMapping("/info/{id}")
    public R info(@PathVariable("id") Long id){
        news news = newsService.selectById(id);
        return R.ok().put("data", news);
    }

    /**
     * 修改
     * @param news
     * @param request
     * @return
     */
    @PostMapping("/update")
    @Transactional
    public R update(@RequestBody news news,HttpServletRequest request){
        newsService.updateById(news);
        return R.ok();
    }

    /**
     * 管理员界面新增
     * @param news
     * @param request
     * @return
     */
    @PostMapping("/save")
    public R sava(@RequestBody news news,HttpServletRequest request){
        news.setId(new Date().getTime()+new Double(Math.floor(Math.random()*10000)).longValue());
        log.info("news:{}",news);
        newsService.insert(news);
        return R.ok();
    }
}
